package com.zhugang.week02;

import java.util.HashSet;
import java.util.Set;

/**
 * @program algorithms
 * @description: hasCycle
 * @author: chanzhugang
 * @create: 2022/05/31 17:34
 */
public class HasCycle {

    /**
     * 141. 环形链表
     *
     * @param head
     * @return
     */
    public boolean hasCycle(ListNode head) {
        // 快慢指针，快指针等于慢指针，表示追上了，有环
        if (head == null) {
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (fast != null && fast.next != null && slow != fast) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow == fast;
    }

    public boolean hasCycle2(ListNode head) {
        // 遍历链表，放入Set，是否在Set中，如果在则表示有环
        Set<ListNode> set = new HashSet<>();
        ListNode p = head;
        while (p != null) {
            if (set.contains(p)) {
                return true;
            }
            set.add(p);
            p = p.next;
        }
        return false;
    }

    class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
            next = null;
        }
    }
}